package com.liao.rent.config;

import com.liao.rent.constant.ResultCode;
import com.liao.rent.filter.JWTAuthenticationFilter;
import com.liao.rent.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;

/**
 * @Author: ljt
 * @Description: web security配置类
 * @DateTime: 2024/11/24 下午4:00
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig {

    @Lazy
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    JWTAuthenticationFilter jwtAuthenticationFilter;

    //    自定义认证管理器
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) {
//        匹配合适的DaoAuthenticationProvider
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
//        设置用户服务的实现类
        provider.setUserDetailsService(userDetailsService);
//        返回认证管理器
        return new ProviderManager(provider);
    }

    //    添加密码加密器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 配置全局的某些通用事物，例如静态资源等
     * @return
     */
    @Bean
    public WebSecurityCustomizer securityCustomizer() {
        return (web) -> web.ignoring().requestMatchers("/static/**", "/webjars/**");
    }


    //security过滤器链
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

//        设置请求拦截
        http.authorizeHttpRequests((auth -> {
                    auth
//                放行请求

//  放行api文档请求
                            .requestMatchers("/sysUser/regist").permitAll()
                            .requestMatchers("/swagger-ui.html").permitAll()
                            .requestMatchers("/v3/**").permitAll()
                            .requestMatchers("/doc.html").permitAll()
                            .requestMatchers("/sysUser/login").permitAll()
                            .requestMatchers("/swagger-ui/**").permitAll()
//                所有请求都需要权限访问
                            .anyRequest().authenticated();
                }))
//                添加自定义过滤器
                .addFilterBefore(jwtAuthenticationFilter, AuthorizationFilter.class)
//                关闭网页登录
                .formLogin(AbstractHttpConfigurer::disable)
                .sessionManagement(sesion -> sesion.disable())
                .exceptionHandling(e -> {
//                    登录失败处理
                    e.authenticationEntryPoint((request, response, authException) ->{
//                        获取请求中的异常信息
                        String errMsg = (String) request.getAttribute("errMsg");
                        ResponseUtil.write(response,errMsg);
                            });
//授权异常处理
                    e.accessDeniedHandler((request, response, accessDeniedException) ->
                            ResponseUtil.write(response, ResultCode.ACCESS_FAIL));
                })
//关闭csrf防护
                .csrf(csrf -> csrf.disable());

        return http.build();


    }


}
